<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="请输入密码查看" v-model="visible" append-to-body width="500px" @close="handleClose">
    <el-form label-position="top">
      <el-form-item label="登录密码" :error="errMessage">
        <el-input v-model="form.inputValue" placeholder="请输入" class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">查 看</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import { ElMessage } from 'element-plus'
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const errMessage = ref('')

const emit = defineEmits(['close', 'success'])

// 打开弹窗
const open = async (password_type, shop_id) => {
  form.value = { inputValue: '', shop_id, password_type }
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  errMessage.value = ''
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

// 设置定时器
const timers = reactive({})
const setTimer = () => {
  const { password_type } = form.value
  timers[password_type] = setTimeout(() => {
    clearTimeout(timers[password_type])
    emit('success', { [password_type]: false })
  }, 60000 * 3)
}

// 清空定时器
const clearTimer = () => {
  for (const key in timers) {
    clearTimeout(timers[key])
    timers[key] = null
  }
}

// 提交
const submit = async () => {
  loadings.submit = true
  if (!form.value.inputValue) {
    errMessage.value = '密码不能为空'
    loadings.submit = false
    return
  }
  try {
    const res = await api.verifyPassword({ password: form.value.inputValue })
    const { flag } = res.data
    if (!flag) {
      errMessage.value = '密码不正确'
    } else {
      errMessage.value = ''
      const { shop_id, password_type } = form.value
      const isImage = password_type === 'verify_image'
      const res = await api[isImage ? 'verifyImage' : 'password']({ shop_id, password_type })
      const { password, verify_image } = res.data
      ElMessage.success('查看成功')
      setTimer()
      emit('success', { [password_type]: isImage ? ([verify_image] || []) : password })
      close()
    }
  } catch (error) {
    errMessage.value = error
  }
  loadings.submit = false
}

defineExpose({ open, clearTimer })
</script>